<template>
  <div class="body">
    <header class="header">
      <div class="title">
        <img src="../../../assets/images/01_11.png" alt="" class="img_zuo" @click="back" />
        <div>地图</div>
      </div>
    </header>
    <div class="main top" id="ditu"></div>
    <div class="list_addss">
      <div class="list_addss_item" :class="{'active':index==0}" v-for="(item, index) in lists" :key="index"
        @click="markUser(item.location)">{{item.name}}</div>
    </div>
  </div>
</template>

<script>
	import utils from "../../../assets/js/utils.js"
  import qs from 'qs';
  export default {
    name: 'dwxc_1_calendar',
    data() {
      return {
        map: null,
        centralpoint: ["106.57", "29.55"],//中心点
        lists: null,//列表地址
      }
    },
    mounted() {
      var _this = this;

    },

    //进入该页面时，用之前保存的滚动位置赋值
    methods: {
      //  返回
      back() {
        // this.$router.push("/dwxc_2_Pointcreation");
        this.$router.back()
      },
      inof() {
        // 创建地图
        this.map = new AMap.Map('ditu', {
          resizeEnable: true,
          zoomEnable: true, //地图是否可缩放，默认值为true
        });
        // 设置中心点
        this.map.setCenter(this.centralpoint);
        // 设置地图级别 // PC上，参数zoom可设范围：[3,18]；// 移动端：参数zoom可设范围：[3,19]
        this.map.setZoom(16);
        // this.mapmarker()
        this.startGeolocation()
      },
      markUser(lnglat) {//用户标点
        // console.log(lnglat)
        var _this = this;
        var img_url = require('../../../assets/images/dwxc/dwpc_25.gif');
        var content = '';
        content += '<div class="user" style="text-align:center;">';
        content += '<img style="width: 0.379629rem;height: 0.462962rem;" src="' + img_url + '"/>';
        content += '</div>';
        // 创建一个 Marker 实例：
        if (_this.userMarker) {
          _this.userMarker.setPosition([lnglat.lng, lnglat.lat]);
          _this.map.setCenter([lnglat.lng, lnglat.lat]);

          // return false
        } else {

          var user_marker = new AMap.Marker({
            position: [lnglat.lng, lnglat.lat],// 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
            //title: '标点',
            content: content,
            zIndex: 110,
            zoom: 19,
            // anchor:'center', // 设置锚点方位
          });

          this.map.setCenter([lnglat.lng, lnglat.lat]);
          // 设置点标记的动画效果，此处为弹跳效果
          //marker.setAnimation('AMAP_ANIMATION_BOUNCE');
          // 将创建的点标记添加到已有的地图实例：
          //marker.dataObj = obj;
          _this.map.add(user_marker);
          _this.userMarker = user_marker;
        }
        _this.aMapSearchNearBy([lnglat.lng, lnglat.lat])
      },

      inof1() {//获取列表
        try {
          plus.nativeUI.showWaiting("正在加载...");
        } catch (e) {
          console.log("plus问题");
        }
        var params = {
          dwId: this.userid,
          dataId: this.dataid
        }
        this.axios
          .post(
            `${this.$global_msg.Url.host}/DotPlacePatrol/getSpotInspectionRecord`, qs.stringify(params)
          )
          .then((res) => {
            try {
              plus.nativeUI.closeWaiting();
            } catch (e) {
              console.log("plus问题");
            }
            console.log(res);
            if (res.data.code == 200) {
              this.list = res.data.rows.list
              this.inof()
            } else {
              this.$toast(res.data.msg);
            }
          });
      },
      startGeolocation() {//开始定位
        var _this = this;
        _this.geolocation_timer = null;
        _this.map.plugin('AMap.Geolocation', function () {
          var geolocation = new AMap.Geolocation({
            // 是否使用高精度定位，默认：true
            enableHighAccuracy: true,
            // 设置定位超时时间，默认：无穷大
            //timeout: 10000,
            // 定位按钮的停靠位置的偏移量，默认：Pixel(10, 20)
            // buttonOffset: new AMap.Pixel(10, 20),
            //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
            zoomToAccuracy: true,
            // noIpLocate:1,
            //  定位按钮的排放位置,  RB表示右下
            //buttonPosition: 'RB'
            // noIpLocate: 1,
          })
          geolocation.getCurrentPosition();
          // 监听获取位置信息成功的回调函数
          AMap.event.addListener(geolocation, 'complete', onComplete);
          // 监听获取位置信息错误的回调函数
          AMap.event.addListener(geolocation, 'error', onError);

          function usePosition(lng,lat){
            _this.jwd_me = lng + "," + lat;
            console.log(_this.jwd_me)
            var gpsPoint = GPS.gcj_decrypt(lat, lng);
            console.log(gpsPoint)
            if (_this.terminal !== true) {
              _this.markUser({ lat: gpsPoint.lat, lng: gpsPoint.lon });
            } else {
              _this.markUser({ lat: lat, lng: lng });
              // _this.markUser({lat:gpsPoint.lat,lng:gpsPoint.lon});
            }
          }

          function onComplete(data) {
            usePosition(data.position.lng,data.position.lat);
          }

          function onError(error) {
            // 定位出错
            //console.log(error)
            utils.getPosition(function(lng,lat){
              console.log('切换使用sdk获取定位成功:'+lng+','+lat);
              usePosition(lng,lat);
            },function(msg){
              console.log('获取定位错误:'+msg);
            });
          }


          var GPS = {
            PI: 3.14159265358979324,
            x_pi: 3.14159265358979324 * 3000.0 / 180.0,
            delta: function (lat, lon) {
              // Krasovsky 1940
              //
              // a = 6378245.0, 1/f = 298.3
              // b = a * (1 - f)
              // ee = (a^2 - b^2) / a^2;
              var a = 6378245.0; //  a: 卫星椭球坐标投影到平面地图坐标系的投影因子。
              var ee = 0.00669342162296594323; //  ee: 椭球的偏心率。
              var dLat = this.transformLat(lon - 105.0, lat - 35.0);
              var dLon = this.transformLon(lon - 105.0, lat - 35.0);
              var radLat = lat / 180.0 * this.PI;
              var magic = Math.sin(radLat);
              magic = 1 - ee * magic * magic;
              var sqrtMagic = Math.sqrt(magic);
              dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * this.PI);
              dLon = (dLon * 180.0) / (a / sqrtMagic * Math.cos(radLat) * this.PI);
              return { 'lat': dLat, 'lon': dLon };
            },

            //WGS-84 to GCJ-02
            gcj_encrypt: function (wgsLat, wgsLon) {
              if (this.outOfChina(wgsLat, wgsLon))
                return { 'lat': wgsLat, 'lon': wgsLon };

              var d = this.delta(wgsLat, wgsLon);
              return { 'lat': wgsLat + d.lat, 'lon': wgsLon + d.lon };
            },
            //GCJ-02 to WGS-84
            gcj_decrypt: function (gcjLat, gcjLon) {
              if (this.outOfChina(gcjLat, gcjLon))
                return { 'lat': gcjLat, 'lon': gcjLon };

              var d = this.delta(gcjLat, gcjLon);
              return { 'lat': gcjLat - d.lat, 'lon': gcjLon - d.lon };
            },
            //GCJ-02 to WGS-84 exactly
            gcj_decrypt_exact: function (gcjLat, gcjLon) {
              var initDelta = 0.01;
              var threshold = 0.000000001;
              var dLat = initDelta, dLon = initDelta;
              var mLat = gcjLat - dLat, mLon = gcjLon - dLon;
              var pLat = gcjLat + dLat, pLon = gcjLon + dLon;
              var wgsLat, wgsLon, i = 0;
              while (1) {
                wgsLat = (mLat + pLat) / 2;
                wgsLon = (mLon + pLon) / 2;
                var tmp = this.gcj_encrypt(wgsLat, wgsLon)
                dLat = tmp.lat - gcjLat;
                dLon = tmp.lon - gcjLon;
                if ((Math.abs(dLat) < threshold) && (Math.abs(dLon) < threshold))
                  break;

                if (dLat > 0) pLat = wgsLat; else mLat = wgsLat;
                if (dLon > 0) pLon = wgsLon; else mLon = wgsLon;

                if (++i > 10000) break;
              }
              //console.log(i);
              return { 'lat': wgsLat, 'lon': wgsLon };
            },
            //GCJ-02 to BD-09
            bd_encrypt: function (gcjLat, gcjLon) {
              var x = gcjLon, y = gcjLat;
              var z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * this.x_pi);
              var theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * this.x_pi);
              bdLon = z * Math.cos(theta) + 0.0065;
              bdLat = z * Math.sin(theta) + 0.006;
              return { 'lat': bdLat, 'lon': bdLon };
            },
            //BD-09 to GCJ-02
            bd_decrypt: function (bdLat, bdLon) {
              var x = bdLon - 0.0065, y = bdLat - 0.006;
              var z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * this.x_pi);
              var theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * this.x_pi);
              var gcjLon = z * Math.cos(theta);
              var gcjLat = z * Math.sin(theta);
              return { 'lat': gcjLat, 'lon': gcjLon };
            },
            //WGS-84 to Web mercator
            //mercatorLat -> y mercatorLon -> x
            mercator_encrypt: function (wgsLat, wgsLon) {
              var x = wgsLon * 20037508.34 / 180.;
              var y = Math.log(Math.tan((90. + wgsLat) * this.PI / 360.)) / (this.PI / 180.);
              y = y * 20037508.34 / 180.;
              return { 'lat': y, 'lon': x };
              /*
              if ((Math.abs(wgsLon) > 180 || Math.abs(wgsLat) > 90))
                  return null;
              var x = 6378137.0 * wgsLon * 0.017453292519943295;
              var a = wgsLat * 0.017453292519943295;
              var y = 3189068.5 * Math.log((1.0 + Math.sin(a)) / (1.0 - Math.sin(a)));
              return {'lat' : y, 'lon' : x};
              //*/
            },
            // Web mercator to WGS-84
            // mercatorLat -> y mercatorLon -> x
            mercator_decrypt: function (mercatorLat, mercatorLon) {
              var x = mercatorLon / 20037508.34 * 180.;
              var y = mercatorLat / 20037508.34 * 180.;
              y = 180 / this.PI * (2 * Math.atan(Math.exp(y * this.PI / 180.)) - this.PI / 2);
              return { 'lat': y, 'lon': x };
              /*
              if (Math.abs(mercatorLon) < 180 && Math.abs(mercatorLat) < 90)
                  return null;
              if ((Math.abs(mercatorLon) > 20037508.3427892) || (Math.abs(mercatorLat) > 20037508.3427892))
                  return null;
              var a = mercatorLon / 6378137.0 * 57.295779513082323;
              var x = a - (Math.floor(((a + 180.0) / 360.0)) * 360.0);
              var y = (1.5707963267948966 - (2.0 * Math.atan(Math.exp((-1.0 * mercatorLat) / 6378137.0)))) * 57.295779513082323;
              return {'lat' : y, 'lon' : x};
              //*/
            },
            // two point's distance
            distance: function (latA, lonA, latB, lonB) {
              var earthR = 6371000.;
              var x = Math.cos(latA * this.PI / 180.) * Math.cos(latB * this.PI / 180.) * Math.cos((lonA - lonB) * this.PI / 180);
              var y = Math.sin(latA * this.PI / 180.) * Math.sin(latB * this.PI / 180.);
              var s = x + y;
              if (s > 1) s = 1;
              if (s < -1) s = -1;
              var alpha = Math.acos(s);
              var distance = alpha * earthR;
              return distance;
            },
            outOfChina: function (lat, lon) {
              if (lon < 72.004 || lon > 137.8347)
                return true;
              if (lat < 0.8293 || lat > 55.8271)
                return true;
              return false;
            },
            transformLat: function (x, y) {
              var ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * Math.sqrt(Math.abs(x));
              ret += (20.0 * Math.sin(6.0 * x * this.PI) + 20.0 * Math.sin(2.0 * x * this.PI)) * 2.0 / 3.0;
              ret += (20.0 * Math.sin(y * this.PI) + 40.0 * Math.sin(y / 3.0 * this.PI)) * 2.0 / 3.0;
              ret += (160.0 * Math.sin(y / 12.0 * this.PI) + 320 * Math.sin(y * this.PI / 30.0)) * 2.0 / 3.0;
              return ret;
            },
            transformLon: function (x, y) {
              var ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * Math.sqrt(Math.abs(x));
              ret += (20.0 * Math.sin(6.0 * x * this.PI) + 20.0 * Math.sin(2.0 * x * this.PI)) * 2.0 / 3.0;
              ret += (20.0 * Math.sin(x * this.PI) + 40.0 * Math.sin(x / 3.0 * this.PI)) * 2.0 / 3.0;
              ret += (150.0 * Math.sin(x / 12.0 * this.PI) + 300.0 * Math.sin(x / 30.0 * this.PI)) * 2.0 / 3.0;
              return ret;
            }
          };

          // 自动适配到合适视野范围
          // 无参数，默认包括所有覆盖物的情况
          // _this.map.setFitView();
        })
      },
      stopGeolocation() {//停止定位
        clearInterval(this.geolocation_timer);
        this.geolocation_timer = null;
      },
      aMapSearchNearBy(centerPoint) {//获取附近周边地标建筑列表
        // console.log(centerPoint)
        var _this = this
        AMap.service(["AMap.PlaceSearch"], function () {
          var placeSearch = new AMap.PlaceSearch({
            pageSize: 50,    // 每页10条
            pageIndex: 1,    // 获取第一页
            // city: city       // 指定城市名(如果你获取不到城市名称，这个参数也可以不传，注释掉)
          });
          // 第一个参数是关键字，这里传入的空表示不需要根据关键字过滤
          // 第二个参数是经纬度，数组类型
          // 第三个参数是半径，周边的范围
          // 第四个参数为回调函数
          placeSearch.searchNearBy('', centerPoint, 1000, function (status, result) {
            console.log("status:", status)
            console.log("result:", result)
            if (result.info === 'OK') {
              var locationList = result.poiList.pois; // 周边地标建筑列表
              console.log(locationList)
              // 生成地址列表html
              _this.lists = locationList
              // createLocationHtml(locationList);
            } else {
              console.log('获取位置信息失败!');
            }
          });
        });
      },
      // current(lnglat){

      // }

    },
    created() {

    },
    mounted() {
      // this.inof1()
      this.inof()
    },

  }
</script>

<style scoped>
  /* 头部 */
  .header {
    height: 1.8519rem;
    background: #007aff;
    padding-top: 0.8333rem;
    box-sizing: border-box;
    width: 100%;
    z-index: 20;
    font-size: 0.388888rem;
    position: fixed;
    top: 0;
    left: 0;
  }

  .title {
    padding: 0 0.3704rem;
    display: flex;
    align-items: center;
    color: #fff;
  }

  .title>div {
    width: 100%;
    font-size: 0.4444rem;
    text-align: center;
  }

  .img_zuo {
    width: 0.2593rem;
    height: 0.463rem;
  }

  .img_jia {
    width: 0.4444rem;
    position: absolute;
    right: 0.3704rem;
  }

  /*  */
  .main {
    flex: 1;
    height: 100vh;
  }

  .list_addss {
    width: 100%;
    position: absolute;
    left: 0;
    bottom: 0;
    height: 6.9444rem;
    background: #fff;
    overflow-y: auto;
  }

  .list_addss_item {
    border-bottom: 1Px solid #ccc;
    height: 1.3889rem;
    box-sizing: border-box;
    overflow: hidden;
    word-break: keep-all;
    text-overflow: ellipsis;
    font-size: 0.3889rem;
    line-height: 1.3889rem;
    padding-left: 0.3704rem;
  }

  .active {
    background: #2D5DFD;
    color: #fff;
  }
</style>